package com.gp.shaw.netty.nio.im;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gp.shaw.netty.nio.im.model.IMMsg;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by asus on 2018/11/7.
 */
public class ReadMsg {
    public static List<IMMsg> read(SocketChannel channel) {
        List<IMMsg> msgList = new ArrayList<>();
        ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
        byte[] bytes = new byte[0];
        try {
//            while (channel.read(byteBuffer) != -1) {
            channel.read(byteBuffer);
            byteBuffer.flip();
            bytes = new byte[byteBuffer.remaining()];
            int pos = bytes.length;
//                System.arraycopy(bytes, 0, newbyte, 0, bytes.length);
            byteBuffer.get(bytes);
//                System.arraycopy(bytes, 0, newbyte, pos, bytes.length);
//                bytes = newbyte;
//            }
            String jsonMsg = new String(bytes, "UTF-8");
            String[] msgs= jsonMsg.split(SendMsg.MSG_END);
            for(int i = 0;i<msgs.length;i++) {
                String msgStr = msgs[i];
                //TODO将JSO能转换成IMMsg对象；
                JSONObject jsonObject = JSON.parseObject(msgStr);
                if (jsonObject == null) {
                    return null;
                }
                IMMsg msg = JSON.toJavaObject(jsonObject, IMMsg.class);
                msgList.add(msg);
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msgList;
    }

}
